#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
下载 pixi-live2d-display 的构建文件到本地
"""

import urllib.request
import os
from pathlib import Path

def download_file(url, dest_path, file_name):
    """下载文件并显示进度"""
    print(f"\n正在下载 {file_name}...")
    print(f"URL: {url}")
    
    try:
        # 创建请求
        req = urllib.request.Request(
            url,
            headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        )
        
        # 下载文件
        with urllib.request.urlopen(req, timeout=60) as response:
            total_size = int(response.headers.get('Content-Length', 0))
            downloaded = 0
            
            # 写入文件
            with open(dest_path, 'wb') as f:
                while True:
                    chunk = response.read(8192)
                    if not chunk:
                        break
                    f.write(chunk)
                    downloaded += len(chunk)
                    
                    if total_size > 0:
                        progress = (downloaded / total_size) * 100
                        print(f"\r进度: {progress:.1f}% ({downloaded}/{total_size} bytes)", end='')
        
        print(f"\n✓ {file_name} 下载完成!")
        return True
        
    except Exception as e:
        print(f"\n✗ 下载失败: {e}")
        return False

def main():
    # 创建 libs 目录
    libs_dir = Path(__file__).parent / 'libs'
    libs_dir.mkdir(exist_ok=True)
    
    print("=" * 70)
    print("下载 pixi-live2d-display 库文件到本地")
    print("=" * 70)
    
    # 要下载的文件列表
    files = [
        {
            'name': 'pixi-live2d-display (完整版 - UMD浏览器版本)',
            'url': 'https://unpkg.com/pixi-live2d-display@0.5.0-beta.5/dist/index.min.js',
            'filename': 'pixi-live2d-display.min.js'
        },
        {
            'name': 'pixi-live2d-display (仅Cubism4 - UMD浏览器版本)',
            'url': 'https://unpkg.com/pixi-live2d-display@0.5.0-beta.5/dist/cubism4.min.js',
            'filename': 'pixi-live2d-display-cubism4.min.js'
        }
    ]
    
    # 下载每个文件
    success_count = 0
    for file_info in files:
        dest_path = libs_dir / file_info['filename']
        
        # 如果文件已存在,跳过
        if dest_path.exists():
            print(f"\n{file_info['name']} 已存在,跳过下载")
            success_count += 1
            continue
        
        # 下载文件
        if download_file(file_info['url'], dest_path, file_info['name']):
            success_count += 1
    
    print("\n" + "=" * 70)
    print(f"下载完成! 成功: {success_count}/{len(files)}")
    print(f"文件保存在: {libs_dir.resolve()}")
    print("=" * 70)

if __name__ == '__main__':
    main()
